package cn.wolfcode.luowowo.website.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理cookie的工具类
 */
public interface CookieUtils {

    /**
     * 添加cookie
     *
     * @param name     cookie的name
     * @param value    cookie的value
     * @param time     cookie的最大存活时间
     * @param response
     */
    static void addCookie(String name, String value, Integer time, HttpServletResponse response) {
        if (name == null || value == null) {
            throw new RuntimeException("name或value为null");
        }
        Cookie cookie = new Cookie(name, value);
        // 设置cookie最大存活时间
        cookie.setMaxAge(time);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    static String getToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
